import { GetGroupTreeList, hotIssues, LicenseEditionEnum } from '@/common/types';
import { create } from 'zustand';
import { produce } from 'immer';
import { getItem, setItem, removeItem } from '@/utils/storage';
import { StorageEnum } from '@/types/enum';
import appService from '@/api/services/appService';
import { DatasetTypeEnum, UpdateBrandingInfo } from '@/common/types';
import userService from '@/api/services/userService';
const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
const licenseFlag = LICENSEFLAG === 'true' ? true : false;

type ConfigType = {
  id?: string;
  share_id?: string;
  title?: string;
  logo_path?: string;
};

type AppType = {
  id?: string;
  share_id?: string;
  debug?: boolean;
};

type InitializeType = {
  enable_role_conditions?: boolean;
  enable_knowledge_governance?: boolean;
  enable_permission_share?: boolean;
  max_supported_file_count?: number;
  max_supported_single_file_size?: number;
  login_page_display?: boolean;
  preview_file_types?: string;
  debug?: boolean;
  app?: AppType;
  is_license_valid?: boolean;
  license_edition?: string;
  is_knowledge_manager?: boolean;
  is_knowledge_reviewer?: boolean;
  use_legacy_version?: boolean;
  allowLocalAccount?: boolean;
  enableMetahuman?: boolean;
};

type OrgManageTree = {
  activeValue?: GetGroupTreeList;
  expandedKeys: string[];
};

type ConfigStore = {
  workBench: string;
  config: ConfigType;
  initializeData: InitializeType;
  appInfo: UpdateBrandingInfo | null;
  linkParams: Record<string, string>;
  homePage: string;
  managePage: string;
  chatPage: string;
  chatId: string;
  hotIssueList: hotIssues[];
  datasetFlag: boolean;
  apiFlag: boolean;
  datasetPermit: any[];
  chatRecordLoading: boolean;
  orgManageTree: OrgManageTree; // 组织管理树形数据
  isKnow: boolean;
  actions: {
    setConfig: (config: ConfigType) => void;
    clearConfig: () => void;
    fetchAppInfo: (id: string) => Promise<void>;
    fetchInitialInfo: () => InitializeType;
    setLinkParams: (params: Record<string, string>) => void;
    fetchPermitFlag: () => Promise<void>;
    setChatRecordLoading: (loading: boolean) => void;
    setOrgManageTree: (value: GetGroupTreeList, change?: boolean, open?: boolean) => void;
    setIsKnow: (value: boolean) => void;
  };
};

const updateConfig = (set: any, newConfig: ConfigType) => {
  setItem(StorageEnum.Config, newConfig);
  set({ config: newConfig });
};

const clearConfigStorage = (set: any) => {
  removeItem(StorageEnum.Config);
  removeItem(StorageEnum.TourStorage);
  removeItem(StorageEnum.RoleManage);
  removeItem(StorageEnum.I18N);
  removeItem(StorageEnum.ChunkRefreshKey);
  removeItem(StorageEnum.LoginPageDisplay);
  removeItem(StorageEnum.Dataset);
  removeItem(StorageEnum.DatasetStorage);
  removeItem(StorageEnum.Settings);
  removeItem(StorageEnum.protocolName);
  set({ config: {} });
};

const useConfigStore = create<ConfigStore>((set) => ({
  config: getItem<ConfigType>(StorageEnum.Config) || {},
  initializeData: {
    license_edition: '',
    is_license_valid: true,
    debug: false,
    login_page_display: true,
    enable_role_conditions: false,
    preview_file_types: '',
    enable_knowledge_governance: false,
    max_supported_file_count: 0,
    max_supported_single_file_size: 500,
  },
  appInfo: null,
  linkParams: {},
  homePage: '/homepage',
  managePage: '/management',
  workBench: '/worklayouts/',
  chatPage: '/',
  chatId: '',
  hotIssueList: [],
  datasetFlag: false,
  apiFlag: false,
  datasetPermit: [],
  chatRecordLoading: false,
  orgManageTree: {
    activeValue: undefined,
    expandedKeys: [],
  },
  isKnow: false,
  actions: {
    setConfig: (config) => updateConfig(set, config),
    clearConfig: () => clearConfigStorage(set),
    fetchAppInfo: async (id: string) => {
      try {
        const responseApp = await appService.brandingDetail(id, 'app');
        const {
          logo: logo_path,
          display_name: title,
          hot_issues: hotIssueList = [],
        } = responseApp || {};

        set(
          produce((state: ConfigStore) => {
            state.hotIssueList = hotIssueList;
            state.appInfo = responseApp;
            title && updateConfig(set, { ...state.config, id, title, logo_path });
          }),
        );
      } catch (error) {
        console.error('Error fetching app info:', error);
      }
    },
    fetchPermitFlag: async () => {
      const data = await userService.getRolePermissions();
      let allPermissions: any = [];
      let readData: any[] = [];
      if (Array.isArray(data)) {
        data.forEach((item) => {
          if (item.permissions && item.permissions.length > 0) {
            allPermissions = allPermissions.concat(item.permissions);
          }
        });
        readData =
          allPermissions
            .filter(
              (item: any) =>
                ['read', '*'].includes(item?.action) &&
                (item?.resource_type == DatasetTypeEnum.dataset ||
                  item?.resource_type === DatasetTypeEnum.faq ||
                  item?.resource_type === DatasetTypeEnum.folder),
            )
            .map((item: any) => item?.resource_id) || [];
      }
      const datasetFlag =
        allPermissions.filter(
          (item: any) =>
            (item?.resource_type === DatasetTypeEnum.folder ||
              item?.resource_type === DatasetTypeEnum.dataset ||
              item?.resource_type === DatasetTypeEnum.faq) &&
            ['admin', '*'].includes(item?.action),
        ).length > 0;
      const apiFlag =
        allPermissions.filter(
          (item: any) =>
            item?.resource_type == DatasetTypeEnum.api && ['admin', '*'].includes(item?.action),
        ).length > 0;
      set(
        produce((state: ConfigStore) => {
          state.datasetFlag = datasetFlag;
          state.apiFlag = apiFlag;
          state.datasetPermit = readData;
        }),
      );
    },
    fetchInitialInfo: async () => {
      let isLicenseValid = true;
      let licenseEdition = LicenseEditionEnum.basic;
      if (licenseFlag) {
        // isLicenseValid = true;
        try {
          const license = await userService.fetchLicense();
          isLicenseValid = license?.is_valid;
          licenseEdition = license?.edition;
        } catch (error) {
          isLicenseValid = false;
        }
      }

      try {
        const responseApp = await appService.initialize();
        const {
          debug,
          enable_role_conditions,
          login_page_display,
          max_supported_file_count,
          max_supported_single_file_size,
          enable_knowledge_governance,
          enable_permission_share,
          app,
          is_knowledge_manager,
          is_knowledge_reviewer,
          preview_file_types,
          use_legacy_version,
          allowLocalAccount,
          enableMetahuman,
        } = responseApp || {};

        const isRuiLogin = login_page_display ?? true;
        sessionStorage.setItem(StorageEnum.LoginPageDisplay, isRuiLogin.toString());

        set(
          produce((state: ConfigStore) => {
            // state.chatPage = `/apps/chat/${app.id}/${app.share_id}`;
            state.initializeData = {
              enable_role_conditions,
              login_page_display,
              debug,
              app,
              is_license_valid: isLicenseValid,
              license_edition: licenseEdition,
              max_supported_file_count,
              max_supported_single_file_size,
              enable_knowledge_governance,
              enable_permission_share,
              is_knowledge_reviewer,
              preview_file_types,
              is_knowledge_manager,
              use_legacy_version,
              allowLocalAccount,
              enableMetahuman,
            };
          }),
        );

        // useConfigStore.getState().actions.fetchPermitFlag();
        // if (app?.id) {
        //   useConfigStore.getState().actions.fetchAppInfo(app.id);
        // }

        return responseApp;
      } catch (error) {
        console.error('Error fetching initial info:', error);
      }
    },
    setLinkParams: (params) => {
      set(
        produce((state: ConfigStore) => {
          state.linkParams = params;
          if (params?.id && params?.share_id) {
            state.chatPage = `/apps/chat/${params.id}/${params.share_id}`;
            state.chatId = params.chat_id || '';
          }
        }),
      );
    },
    setChatRecordLoading: (loading: boolean) => {
      set({ chatRecordLoading: loading }); // 更新 chatRecordLoading
    },
    setOrgManageTree: (value: GetGroupTreeList, change?: boolean, open: boolean = true) => {
      set(
        produce((state: ConfigStore) => {
          const { expandedKeys } = state.orgManageTree;
          if (open) {
            state.orgManageTree.activeValue = value;
          }

          if (change) {
            return;
          }

          const index = expandedKeys.findIndex((item) => item === value.id);
          if (index === -1) {
            state.orgManageTree.expandedKeys.push(value.id);
          } else {
            state.orgManageTree.expandedKeys.splice(index, 1);
          }
        }),
      );
    },
    setIsKnow: (value: boolean) => {
      set(
        produce((state: ConfigStore) => {
          state.isKnow = value;
        }),
      );
    },
  },
}));

// 导出 hooks
export const useConfig = () => useConfigStore((state) => state.config);
export const useConfigActions = () => useConfigStore((state) => state.actions);
export const useLinkParams = () => useConfigStore((state) => state.linkParams);
export const useHomePage = () => useConfigStore((state) => state.homePage);
export const useWorkBench = () => useConfigStore((state) => state.workBench);
export const useHotIssueList = () => useConfigStore((state) => state.hotIssueList);
export const useManagePage = () => useConfigStore((state) => state.managePage);
export const useChatPage = () => useConfigStore((state) => state.chatPage);
export const useChatId = () => useConfigStore((state) => state.chatId);
export const useInitializeData = () => useConfigStore((state) => state.initializeData);
export const useDatasetFlag = () => useConfigStore((state) => state.datasetFlag);
export const useDatasetPermit = () => useConfigStore((state) => state.datasetPermit);
export const useApiFlag = () => useConfigStore((state) => state.apiFlag);
export const useInitializeKG = () =>
  useConfigStore((state) => state.initializeData?.enable_knowledge_governance ?? false);
export const useAppInfo = () => useConfigStore((state) => state.appInfo);
export const useConfigState = () => useConfigStore((state) => state);
export const useChatRecordLoading = () => useConfigStore((state) => state.chatRecordLoading);
export const useOrgManageTree = () => useConfigStore((state) => state.orgManageTree);
export const useKnowStatus = () => useConfigStore((state) => state.isKnow);

export default useConfigStore;
